package com.gjp.processdemo.controller;

import com.gjp.processdemo.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.List;

@RestController
@Slf4j
public class ProcessController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 查询流程定义列表
     * @return
     */
    @RequestMapping("/process/list")
    public ModelAndView getProcessList() {
        ModelAndView modelAndView = new ModelAndView("process-list");
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().active().list();
        modelAndView.addObject("processList", list);
        return modelAndView;
    }

    /**
     * 启动流程
     * @param processKey
     * @return
     */
    @RequestMapping("/start/{processKey}")
    public ModelAndView startProcessByKey(@PathVariable("processKey") String processKey) throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView();
        ProcessInstance processInstance;
        try {
            //设置流程启动者
            identityService.setAuthenticatedUserId(UserUtil.getCurrentUsername());
            //启动流程
            processInstance = runtimeService.startProcessInstanceByKey(processKey);
        } finally {
            //清空
            identityService.setAuthenticatedUserId(null);
        }
        log.debug("processInstance：{}", processInstance.getId());
        modelAndView.setViewName("redirect:/myTask");
        return modelAndView;
    }
}
